﻿package com.kuanter.kuanterauto.activity;

import java.util.ArrayList;
import java.util.List;

import org.apache.http.NameValuePair;
import org.apache.http.message.BasicNameValuePair;
import org.json.JSONException;

import android.content.SharedPreferences;
import android.os.Bundle;
import android.os.Handler;
import android.text.InputFilter;
import android.text.method.PasswordTransformationMethod;
import android.view.View;
import android.view.inputmethod.EditorInfo;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.kuanter.kuanterauto.R;
import com.kuanter.kuanterauto.constants.HttpConfigAPI;
import com.kuanter.kuanterauto.constants.MainConstants;
import com.kuanter.kuanterauto.net.HttpTask;
import com.kuanter.kuanterauto.utils.DataLoader;
import com.kuanter.kuanterauto.utils.SharePrefenceUtil;
import com.kuanter.kuanterauto.utils.StringUtil;
import com.umeng.analytics.MobclickAgent;
/**
 * 修改用户密码
 * @author kuanter
 *
 */
public class PersonalInfoPasswordSettingActivity extends WuyangBaseActivity {

	private View itemView;
	private TextView itemTitle;
	private EditText itemData;
	private Button submit_btn;
	private String old_password = "";
	private String new_password = "";
	private String confirm_new_password = "";
	private SharedPreferences sp;
	protected JSONObject jsonObjectResult;
	/**
	 * 请求随机码响应
	 */
	Handler handler = new Handler() {
		public void handleMessage(android.os.Message msg) {
			switch (msg.what) {
			case HttpTask.RESULT_OK:
				finishProgress();
				String result = (String) msg.obj;
				if (!result.equals("网络连接错误")) {
					try {
						if (StringUtil.isSuccess(result)) {// 判断返回数据中 status
							
								jsonObjectResult= JSON.parseObject(result);
								if(null != jsonObjectResult.getString("randomCode")){
									String jsonStr = jsonObjectResult.getString("randomCode");
									randomCode = jsonStr;
									finishProgress();
								}else {
									finishProgress();
//									showToast("成功");
									finish();
								}
						} else {
							finishProgress();
							// 显示返回数据中 errorMsg 字段值
							/*jsonObjectResult= JSON.parseObject(result);
							showToast(jsonObjectResult.getString("errorMsg"));*/
							showToast("新密码与原密码相同");
						}
					} catch (JSONException e) {
						finishProgress();
						showToast("失败");
						e.printStackTrace();
					}
				} else {
					finishProgress();
					showToast("登录失败,网络错误!");
				}
				break;
			case HttpTask.RESULT_ERROR:
				finishProgress();
				showToast("网络错误!");
				break;
			}
		}
	};
//	private TextView please_auth_code_password;
	private int userId;
	private String randomCode;
	private String mobileNumber;
	private View old_password_item;
	private View new_password_item;
	private View confirm_new_password_item;
	
	public void onResume() {
	    super.onResume();
	    MobclickAgent.onResume(this);
	}
	public void onPause() {
	    super.onPause();
	    MobclickAgent.onPause(this);
	}

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		// TODO Auto-generated method stub
		setContentView(R.layout.personal_info_password_setting);
		super.onCreate(savedInstanceState);
		this.setHeaderControlViewText();
		this.initBodyControlView();
		this.registerListener() ;
		this.setBodyControlViewText();
		userId = SharePrefenceUtil.getUserID(this);
		sp = getSharedPreferences(SharePrefenceUtil.USERINFO, MODE_PRIVATE);
	}

	@Override
	public void onClick(View v) {
		switch (v.getId()) {
		case R.id.header_left:
			this.finish();
			break;
		case R.id.header_right://提交修改的数据
			//与服务器交互
			getControlViewText();
			
			//showToast("与服务器交互"+old_password+"+++"+new_password+"+++"+confirm_new_password);
			/*
			if(!"122".equals(old_password)){//模拟服务器返回了旧密码为122
				showToast("模拟服务器返回的旧密码为122,你的填写有误");
				break;
			}*/
			/*if("".equals(old_password)){
				showToast("请输入原密码");
			}else if(old_password.length() != 6){
				showToast("原密码位数错误（6）");
			}else if(! (sp.getString("password", "-1")).equals(old_password)){
				showToast("原密码错误");
			}else */if("".equals(new_password)){
				showToast("请输入新密码");
			}else if(new_password.length() != 6){
				showToast("新密码位数错误（6）");
			}else if("".equals(confirm_new_password)){
				showToast("请确认新密码");
			}else if(confirm_new_password.length() != 6){
				showToast("确认密码位数错误（6）");
			}else if(!new_password.equals(confirm_new_password)){
				showToast("两次输入的新密码不一致");
			}else {
				List<NameValuePair> params = new ArrayList<NameValuePair>();
				params.add(new BasicNameValuePair("password",new_password));
				params.add(new BasicNameValuePair("userId",userId+""));
//				params.add(new BasicNameValuePair("randomCode",randomCode));
				new DataLoader(this).DisplayData(MainConstants.HOST_test+HttpConfigAPI.UPDATE_PASSWORD, params , handler, "", false);
				showProgress("正在加载数据...");
//				showToast("请检查您的输入");
			}
			break;
		/*case R.id.please_auth_code_password:
			List<NameValuePair> params1 = new ArrayList<NameValuePair>();
			SharedPreferences sp = getSharedPreferences("userinfo", MODE_PRIVATE);
			mobileNumber = sp.getString("mobileNumber", "");
			params1.add(new BasicNameValuePair("mobileNumber",mobileNumber));
			params1.add(new BasicNameValuePair("userId",userId+""));
			params1.add(new BasicNameValuePair("email",null));
			new DataLoader(this).DisplayData(MainConstants.HOST_test+HttpConfigAPI.RANDOM_CODE, params1 , handler, "", false);
			showProgress("加载中");
			break;*/
		default:
			break;
		}
	}
	

	@Override
	protected void setHeaderControlViewText() {
		// TODO Auto-generated method stub
		super.setHeaderTitleText(super.headerTitle, "密码设置") ;
		super.setHeaderLeftText(super.headerLeft, "返回");
		super.setHeaderRightText(super.headerRight, "提交");
	}

	@Override
	protected void initBodyControlView() {
		// TODO Auto-generated method stub
		
		old_password_item = findControlView(R.id.old_password_item) ;
		setControlViewText(old_password_item,"原  密  码：");
		
		new_password_item = findControlView(R.id.new_password_item) ;
		setControlViewText(new_password_item,"新  密  码：");
		
		confirm_new_password_item = findControlView(R.id.confirm_new_password_item);
		setControlViewText(confirm_new_password_item,"确认密码：");
		
		submit_btn = (Button)this.findViewById(R.id.header_right);
//		please_auth_code_password = (TextView)this.findViewById(R.id.please_auth_code_password);
	}

	@Override
	protected void registerListener() {
		// TODO Auto-generated method stub
		super.headerLeft.setOnClickListener(this);
		submit_btn.setOnClickListener(this);
//		please_auth_code_password.setOnClickListener(this);
	}

	@Override
	protected void setBodyControlViewText() {
		// TODO Auto-generated method stub
		submit_btn.setText("提 交");
	}

	@Override
	protected void getControlViewText() {
		// TODO Auto-generated method stub
		old_password = getEditTextString(old_password_item);
		new_password = getEditTextString(new_password_item);
		confirm_new_password = getEditTextString(confirm_new_password_item);
	}
	
	/*public void findControlView(int itemId,int tvId,int etId){
		itemView = this.findViewById(itemId);
		itemTitle = (TextView)itemView.findViewById(tvId);
		itemData = (EditText)itemView.findViewById(etId);
		
	}*/
	public View findControlView(int itemId){
		itemView = this.findViewById(itemId);
		itemTitle = (TextView)itemView.findViewById(R.id.include_1tv_1et_true_tv);
		itemData = (EditText)itemView.findViewById(R.id.include_1tv_1et_true_et);
		//设置数字密码输入
		itemData.setTransformationMethod(PasswordTransformationMethod.getInstance());
		itemData.setFilters(new InputFilter[]{ new InputFilter.LengthFilter(6) });
		itemData.setInputType(EditorInfo.TYPE_CLASS_NUMBER);
		return itemView;
	}
	public void setControlViewText(View view,String data){
		TextView itemTitle = (TextView)view.findViewById(R.id.include_1tv_1et_true_tv);
		itemTitle.setText(data);
	}
	public String getEditTextString(View view){
		EditText itemData = (EditText)view.findViewById(R.id.include_1tv_1et_true_et);
		return itemData.getText().toString();
	}
	
}
